﻿using BJoin.Common;
using DapperExtensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace BJoin.Application.IRepository
{
    public static class RepositoryExtension
    {
        public static IList<ISort> OrderByToSort<T>(this string[] orderBy)
        {
            if (null == orderBy || orderBy.IsEmpty())
            {
                return new List<ISort>();
            }
            else
                return Array.ConvertAll(orderBy, value => new Sort<T>
                {
                    PropertyName = value?.ToString().Replace("-", string.Empty),
                    Ascending = !((value?.ToString()).Contains("-"))
                });
        }
        public static IList<ISort> By<T>(this IEnumerable<ISort> me, Expression<Func<T, object>> accessPath, bool asc = false)
        {
            var sorts = me.Concat(new[] { new Sort<T>() 
            {
                PropertyName = accessPath.Properties().LastOrDefault().Name,
                Ascending = asc
            } });
            return sorts.ToList();
        }
        public static void ValidateObjectNotNull(this object predicate)
        {
            if (null == predicate && ReflectionHelper.GetObjectValues(predicate, true).Count == 0) //all fields are null that is invalid
                throw new ArgumentException("delete with no predicate,forbidden operation");
        }
        public class Order
        {
            public static List<ISort> ById<T>(bool asc = false)
            {
                return Order<T>.ById(asc);
            }

            public static List<ISort> By<T>(Expression<Func<T, object>> accessPath, bool asc = false)
            {
                return Order<T>.By(accessPath, asc);
            }
        }

        public class Order<T>
        {
            public static List<ISort> ById(bool asc = false)
            {
                var sorts = new List<ISort>
            {
                new Sort<T>() { PropertyName = "Id", Ascending = asc }
            };

                return sorts;
            }

            public static List<ISort> By(Expression<Func<T, object>> accessPath, bool asc = false)
            {
                var sorts = new List<ISort>
            {
                new Sort<T>() { PropertyName = accessPath.Properties().LastOrDefault().Name, Ascending = asc }
            };

                return sorts;
            }
        }
    }
}
